import axios from 'axios'
import { getToken, removeToken } from './token'

const instance = axios.create({
  baseURL: process.env.VUE_APP_BASEURL,
  withCredentials: true
})

// 请求拦截器
// Add a request interceptor
instance.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    const token = getToken()
    if (token) {
      config.headers.token = token
    }
    return config
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function(response) {
    // Do something with response data
    if (response.data.code === 206) {
      // token过期了
      removeToken()
    }
    return response
  },
  function(error) {
    // Do something with response error
    return Promise.reject(error)
  }
)

export default instance
